package hlhj.com.carviewpad.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Environment
import android.support.v7.widget.TintContextWrapper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.bumptech.glide.Glide
import hlhj.com.carviewpad.R
import hlhj.com.carviewpad.javabean.ContinueEvent
import org.greenrobot.eventbus.EventBus

@SuppressLint("StaticFieldLeak")
/**
 * Created by Never Fear   on 2019\1\18 0018.
Never More....
 */
object Adutil {
    var adId =1111

    var lastVg: ViewGroup?=null

    fun showAd(viewGroup: ViewGroup, mContext: Context, width:Int, height:Int){
        lastVg?.let {
            hideAd(it)
        }
        val lpParent = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        lpParent.gravity= Gravity.CENTER
        val frameLayout = FrameLayout(mContext)
        frameLayout.id= adId

        val adview=LayoutInflater.from(mContext).inflate(R.layout.game,null) as View
        val adParams = FrameLayout.LayoutParams(width, height)

        adParams.gravity= Gravity.CENTER
        frameLayout.addView(adview,adParams)
        viewGroup.addView(frameLayout,lpParent)

        Glide.with(mContext).load(Environment.getExternalStorageDirectory().absolutePath+"/carpad/game/game.jpg").into(adview.findViewById(R.id.img))
        adview?.findViewById<View>(R.id.btDiss)
                .setOnClickListener {
                    EventBus.getDefault().post(ContinueEvent())
                    hide()
                }
        lastVg=viewGroup
    }
    fun hide(){
        lastVg?.let {
            hideAd(it)
        }
    }
    fun hideAd(viewGroup: ViewGroup){
        val flayout = viewGroup.findViewById<FrameLayout>(adId)
        viewGroup.removeView(flayout)
    }
    fun scanForActivity(context: Context?): Activity? {
        if (context == null) return null
        if (context is Activity) {
            return context
        } else if (context is TintContextWrapper) {
            return scanForActivity(context.baseContext)
        } else if (context is ContextWrapper) {
            return scanForActivity(context.baseContext)
        }

        return null
    }

}